package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"log"
	"os"
	"os/exec"
)

// 功能： ansible 功能执行
func Ansible(c *gin.Context) {

	playbook := c.PostForm("playbook")
	argument := c.PostForm("argument")
	token := c.PostForm("token")

	result := PlayBookExec(token, playbook, argument)

	if result {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "success",
		})
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "failed",
		})
	}

}

// 功能：判断文件是否存在
func fileExists(path string) bool {
	_, err := os.Stat(path)
	if err == nil {
		return true
	}
	if os.IsNotExist(err) {
		return false
	}
	return false
}

func PlayBookExec(token string, playbook string, argument string) bool {
	// 判断token 和 playbook 值是否为空
	readToken := viper.GetString("playbook.token")
	if token == "" || playbook == "" {
		log.Printf("token或playbook文件为空，token: %s playbook: %s", token, playbook)
		return false
	} else if token != readToken {
		log.Println("token比对失败，token:", token)
		return false
	}

	// 判断文件是否存在
	playBookPath := viper.GetString("playbook.path")
	if !fileExists(playBookPath) {
		fmt.Println("Ansible playbook 文件不存在。")
		return false
	}

	// playbook 路径组装
	playBookPath = playBookPath + "/" + playbook
	log.Println("playbook路径: ", playBookPath)

	// playbook 参数组装
	argument = fmt.Sprintf("argu=%s", argument)
	log.Println("playbook参数: ", argument)

	// 构建执行 Ansible-playbook 命令
	cmd := exec.Command("ansible-playbook", playBookPath, "-e", argument)

	// 执行命令并捕获输出和错误
	output, err := cmd.CombinedOutput()
	if err != nil {
		log.Println("执行 Ansible playbook 失败：", err)
		return false
	}

	// 打印执行结果
	log.Println("Ansible playbook 执行结果：", string(output))
	return true
}

//func Test() {
//	fmt.Println(w http.ResponseWriter, r *http.Request)
//	r.ParseForm()
//	for key, values := range r.Form {
//		for _, value := range values {
//			fmt.Printf("Parameter %s: %s\n", key, value)
//		}
//	}
//	fmt.Fprintln(w, "Parameters printed.")
//}
